﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BudgetMealsModels.Abstract;
using BudgetMealsModels.Entities;

namespace BudgetMealsUI.Controllers
{
    public class SearchController : Controller
    {
        IRecipeRepository repository;

        public SearchController(IRecipeRepository repo)
        {
            repository = repo;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SearchBar()
        {
            return PartialView();
        }

        public ViewResult SearchResults()
        {
            IEnumerable<Recipe> result = repository.Recipes;
            List<string> keywords = new List<string>();
            string searchString = Request["searchBar"];
            if (searchString != null)
            {
                string[] words = searchString.Split(new char[] {' '});
                foreach (string s in words)
                {
                    if (s != "the" && s != "and")
                    {
                        keywords.Add(s);
                    }
                }
                foreach (string word in keywords)
                {
                    result = Narrow(result, word);
                }
            }
            return View(result);
        }

        public IEnumerable<Recipe> Narrow(IEnumerable<Recipe> result, string word)
        {
            return result = result.Where(x => x.Name.ToLower().Contains(word.ToLower()) || x.RecipeType.ToLower().Contains(word.ToLower()) || x.RecipeEthnicity.ToLower().Contains(word.ToLower()));
        }
    }
}
